#处理一个json文件
import json
from utils import *
with open('src/1.json', 'r')as f:
    a = json.loads(f.read())
json_all_data=[]
for i in range(len(a["shapes"])):
    json_all_data.append({
        a["shapes"][i]["label"]:[int(a["shapes"][i]["points"][0][0]),int(a["shapes"][i]["points"][0][1]),
                                 int(a["shapes"][i]["points"][1][0]),int(a["shapes"][i]["points"][1][1])]
    })
# print(json_all_data)

# p_list=[]
# for i in json_all_data:
#     p_list.append(list(i.values())[0])
# show_with_rs("src/1.jpg",p_list)
height,width=a["imageHeight"],a["imageWidth"]
# 将a,[107, 146, 236, 189]转化为b,[x_center,y_center,w,h]
yolo_all_data=[]
for i in range(len(json_all_data)):
    a=list(json_all_data[i].values())[0]
    b=[((a[0]+a[2])/2)/width,((a[1]+a[3])/2)/height,(a[2]-a[0])/width,(a[3]-a[1])/height]
    yolo_all_data.append({list(json_all_data[i].keys())[0]:b})
#print(yolo_all_data)#[{'eyes': [0.162098, 0.424051, 0.121928, 0.109]}, {'eyes': [0.160681, 0.631646, 0.066163, 0.104]}, {'eyes': [0.566163, 0.406329, 0.075614, 0.089]}, {'eyes': [0.577032, 0.589873, 0.038752, 0.091]}, {'eyes': [0.749055, 0.408861, 0.029301, 0.078]}, {'eyes': [0.743384, 0.593671, 0.029301, 0.109]}]


#获取所有类别
with open("src/classes.txt","r")as f:
    all_cata_str=f.read()
all_cata_list=all_cata_str.split("\n")[:-1]#['eyes', 'mouse']
all_cata_dict={}
for i in range(len(all_cata_list)):
    all_cata_dict[all_cata_list[i]]=str(i)
# print(all_cata_dict)#{'eyes': '0', 'mouse': '1'}

#生成yolo标注文件
content=""
for i in range(len(yolo_all_data)):
    content+=all_cata_dict[list(yolo_all_data[i].keys())[0]]+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][0])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][1])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][2])+" "+\
        "%.6f" %(list(yolo_all_data[i].values())[0][3])+"\n"
with open("result/1.txt","w", encoding='utf-8')as f:
    f.write(content)

with open("result/classes.txt","w", encoding='utf-8')as f:
    f.write(all_cata_str)










